package device

import (
	"alarm_service/common/logger"
	"alarm_service/internal/models"
	"strings"
	"time"

	"gorm.io/gorm"
)

type DeviceRepo struct {
	DB *gorm.DB
}

func (d *DeviceRepo) GetDeviceByIdentifier(identifier string) (*models.Device, error) {
	deviceInfo := models.Device{}
	if err := d.DB.Model(models.Device{}).Where("identifier = ?", identifier).Last(&deviceInfo).Error; err != nil {
		return nil, err
	}
	return &deviceInfo, nil
}

func (d *DeviceRepo) SetDeviceByInfo(deviceInfo *models.Device) error {
	if err := d.DB.Model(deviceInfo).
		Select("status", "device_electricity", "device_oxygen", "device_oxygen_info", "device_water",
			"device_three_electricity", "device_temperature", "device_humidity", "device_standby",
			"device_signal", "device_message_switch", "device_alarm_switch", "device_flood").
		Save(&deviceInfo).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetHeartBeat(id int) error {
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Update("heartbeats_at", time.Now()).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetPhones(id int, phones []string) error {
	phoneStr := strings.Join(phones, ",")
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Update("device_phone", phoneStr).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetMessageSwitch(id int, onOff uint8) error {
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Update("device_message_switch", onOff).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetRecover(id int) error {
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Update("recover_at", time.Now()).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetPhoneSwitch(id int, onOff uint8) error {
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Update("device_phone_switch", onOff).Error; err != nil {
		return err
	}
	return nil
}

func (d *DeviceRepo) SetOffline(id int) {
	now := time.Now()
	if err := d.DB.Model(models.Device{}).Where("id = ?", id).Updates(map[string]interface{}{
		"status":       models.DeviceStatusOffline,
		"p_updated_at": now,
	}).Error; err != nil {
		logger.Errorf("[BatchProcessor] update Device error: %s", err.Error())
	}
}
